# coding=utf-8
"""
# Author : Hunter Oakley
# Time   : 2022/5/30 23:19
# Descripation: 封装的bootstrap组件
"""
from django import forms

class BootStrapStyle(forms.ModelForm):
    """
    在ModelForm中展示BootStrap的样式
    """
    exclude_fileds = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # print(self.fields,type(self.fields)) # 返回的是一个含有fields中定义字段的字典
        # {
        # 'name': < django.forms.fields.CharFieldobject at 0x000001D30EE3C088 >,
        # 'age': < django.forms.fields.IntegerFieldobject at 0x000001D30EE3C288 >,
        # 'gender': < django.forms.fields.TypedChoiceFieldobject at 0x000001D30EE3C408 >,
        # 'password': < django.forms.fields.CharFieldobject at 0x000001D30EE3C488 >,
        #  'depart': < django.forms.models.ModelChoiceFieldobject at 0x000001D30EE3C508 >,
        #  'salary': < django.forms.fields.DecimalFieldobject at 0x000001D30EC77888 >,
        #  'create_time': < django.forms.fields.DateTimeField object at0x000001D30EE3C588 >
        # }

        # 循环所有的字段，给每个字段的插件设置添加class="form-control"的属性
        for name, field in self.fields.items():
            # print(name,field)
            # 也可以加入判断来取消添加属性
            # if name ==  "password":
            #     continue
            if name in BootStrapStyle.exclude_fileds:
                continue

            # 字段中有属性，保留原来的属性，没有属性，才增加
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    "placeholder": field.label
                }



class BootStrapForm(forms.Form):

    exclude_fileds = []
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环所有的字段，给每个字段的插件设置添加class="form-control"的属性
        for name, field in self.fields.items():
            if name in BootStrapForm.exclude_fileds:
                continue
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    "placeholder": field.label
                }

